package com.tju.resource.business.tb_report_order;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbOutwardMapper;
import com.tju.resource.mapper.TbProdPlanMapper;
import com.tju.resource.mapper.TbReportOrderMapper;
import com.tju.resource.model.TbOutward;
import com.tju.resource.model.TbProdPlan;
import com.tju.resource.model.TbReportOrder;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class TbReportOrderServiceImpl implements TbReportOrderService {
    @Autowired
    private ChineseExceptionUtils zh_CH;
    @Autowired
    private TbReportOrderMapper tbReportOrderMapper;
    @Autowired
    private TbProdPlanMapper tbProdPlanMapper;
    @Autowired
    private TbOutwardMapper tbOutwardMapper;

    /**
     * 查询报工
     */
    @Override
    public Result<Object> selectTbReportOrder(Map<String, String> params) {
        try {
            if (EmptyUtils.isNotEmpty(params.get("page")) && EmptyUtils.isNotEmpty(params.get("limit"))) {
                int pageNum = Integer.parseInt(params.get("page"));
                int limit = Integer.parseInt(params.get("limit"));
                Page<TbReportOrder> page = new Page<>(pageNum, limit);
                IPage<TbReportOrder> iPage = tbReportOrderMapper.selectTbReportOrder(page, params);
                List<TbReportOrder> reportOrderList = iPage.getRecords(); //查询结果
                List<TbReportOrder> followNode = new ArrayList<>(); //父级
                for (TbReportOrder reportOrder : reportOrderList) { //查询所有报工
                    if (EmptyUtils.isEmpty(reportOrder.getParentId())) { //拿到父级报工
                        followNode.add(reportOrder); //加到这个集合
                    }
                }
                List<TbReportOrder> children;
                for (TbReportOrder tbReportOrder : followNode) { //循环父级
                    children = new ArrayList<>();  //创建下面级
                    Long id = tbReportOrder.getId(); //拿到父级id
                    for (TbReportOrder reportOrder : reportOrderList) { //循环父级
                        if (id.equals(reportOrder.getParentId())) { //做对比
                            children.add(reportOrder); //加到他下面
                        }
                    }
                    tbReportOrder.setChildren(children); //把子级加到父级
                }

                if (followNode.size() != 0) { //判断父级为空
                    reportOrderList.clear();
                    reportOrderList = followNode;
                }
                return ResultUtil.success(ResultEnum.SUCCESS, reportOrderList, iPage.getTotal());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
    }

    /**
     * 添加报工
     *
     * @param reportOrder
     * @return
     */
    @Override
    @Transactional
    public Result<Object> insertTbReportOrder(TbReportOrder reportOrder) {
        if (EmptyUtils.isNotEmpty(reportOrder.getPpId()) || EmptyUtils.isNotEmpty(reportOrder.getOutwardId())) {
            //根据报工的生产计划id查询工艺
            List<TbProdPlan> tbProdPlanList = new ArrayList<>();
            if (EmptyUtils.isNotEmpty(reportOrder.getPpId()))
                tbProdPlanList = tbProdPlanMapper.TbProdPlanById(reportOrder.getPpId());
            //根据报工的外发id查询工艺
            List<TbOutward> outwardList = new ArrayList<>();
            if (EmptyUtils.isNotEmpty(reportOrder.getOutwardId()))
                outwardList = tbOutwardMapper.outwardById(reportOrder.getOutwardId());
            if (EmptyUtils.isEmpty(tbProdPlanList) && EmptyUtils.isEmpty(outwardList))
                throw new ServiceException("请选择需要的工艺流程!");
            if (reportOrder.getReportQty() <= 0) {
                throw new ServiceException("请输入报工数量!");
            }
            if (EmptyUtils.isEmpty(reportOrder.getOnFrom())) {
                if (EmptyUtils.isNotEmpty(reportOrder.getPpId())) {
                    TbProdPlan tbProdPlan = new TbProdPlan();
                    tbProdPlan.setId(reportOrder.getPpId());//生产计划id
                    tbProdPlan.setReportState(1);//状态为1
                    tbProdPlanMapper.updateById(tbProdPlan); //修改为报工过
                }
                if (tbProdPlanList.size() < 2 && outwardList.size() < 2)
                    throw new ServiceException("该工艺流程没有下一步,请选择有下一步的工艺流程!");
                if (EmptyUtils.isNotEmpty(tbProdPlanList)) {
                    reportOrder.setOnFrom(tbProdPlanList.get(0).getProcessCode());  //工艺第一步
                    reportOrder.setToWhere(tbProdPlanList.get(1).getProcessCode()); //工艺下一步
                } else {
                    reportOrder.setOnFrom(outwardList.get(0).getProcessCode());  //工艺第一步
                    reportOrder.setToWhere(outwardList.get(1).getProcessCode()); //工艺下一步
                }
                reportOrder.setCurStep(1);
            } else {
                int curStepIndex = reportOrder.getCurStep() + 1;
                if (EmptyUtils.isEmpty(reportOrder.getId()))
                    throw new ServiceException("不存在报工!");
                TbReportOrder tbReportOrder = tbReportOrderMapper.selectById(reportOrder.getId());
                tbReportOrder.setFinished(1); //审核状态
                tbReportOrderMapper.updateById(tbReportOrder);
                if (tbReportOrder.getReportQty() < reportOrder.getReportQty())
                    throw new ServiceException("报工数量不能大于原先报工数!");
                if (EmptyUtils.isEmpty(reportOrder.getParentId()))
                    reportOrder.setParentId(reportOrder.getId()); //报工父级id
                reportOrder.setId(null);
                reportOrder.setOnFrom(reportOrder.getToWhere()); //上一个工序
                //判断到最后了
                if (EmptyUtils.isNotEmpty(tbProdPlanList)) {  //判断生产计划不为空 就进入
                    if (tbProdPlanList.size() > curStepIndex)
                        reportOrder.setToWhere(tbProdPlanList.get(curStepIndex).getProcessCode()); //下一个工序
                    else reportOrder.setToWhere(null);
                } else { //否者就是外发
                    if (outwardList.size() > curStepIndex)
                        reportOrder.setToWhere(outwardList.get(curStepIndex).getProcessCode()); //下一个工序
                    else reportOrder.setToWhere(null);
                }
                reportOrder.setCurStep(curStepIndex); //所在工序
            }
            if (tbReportOrderMapper.insert(reportOrder) > 0) {  //添加
                Result<Object> success = ResultUtil.success(ResultEnum.SUCCESS, "报工成功!");
                success.setData(reportOrder.getId());
                return success;
            }
        } else {
            throw new ServiceException("请输入生产id或外发id!");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "报工失败!");
    }

    /**
     * 修改报工
     *
     * @param reportOrder
     * @return
     */
    @Override
    @Transactional
    public Result<Object> updateTbReportOrder(TbReportOrder reportOrder) {
        if (EmptyUtils.isNotEmpty(reportOrder.getId())) {
            if (tbReportOrderMapper.updateById(reportOrder) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyModified);
            }
        } else {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailToEdit);
    }

    /**
     * 删除报工
     *
     * @param reportOrder
     * @return
     */
    @Transactional
    @Override
    public Result<Object> deleteTbReportOrder(TbReportOrder reportOrder) {
        if (EmptyUtils.isNotEmpty(reportOrder.getId())) {
            if (tbReportOrderMapper.deleteById(reportOrder.getId()) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyDeleted);
            }
        } else {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailedToDelete);
    }
}




